<template>
  <div class="home-goods">
    <MyPanel title="推荐商品" subTitle="精选好物 为您推荐">
      <ul v-if="goods.length" class="goods-list">
        <li class="item" v-for="item in goods" :key="item.productId">
          <div class="goods-container">
            <!-- 商品图片 -->
            <div class="goods-image">
              <img :src="item.imageUrl" :alt="item.productName" />
            </div>
            
            <!-- 商品名称 -->
            <div class="goods-name ellipsis">{{ item.productName }}</div>
            
            <!-- 价格和购物车按钮 -->
            <div class="goods-price">
              <span class="price">￥{{ item.price }}</span>
              <div class="add-cart-btn" @click="addToCart(item)">
                <span>+</span>
              </div>
            </div>
            
            <!-- 购买按钮 -->
            <div class="buy-btn">
              <button class="purchase-btn" @click="buyNow(item)">立即购买</button>
            </div>
          </div>
        </li>
      </ul>
      
      <!-- 骨架屏 -->
      <div v-else class="goods-list skeleton-list">
        <el-skeleton v-for="i in 8" :key="i" style="width: 265px">
          <template #template>
            <el-skeleton-item variant="image" style="width: 240px; height: 240px" />
            <div style="padding: 14px">
              <el-skeleton-item variant="p" style="width: 50%" />
              <div
                style="
            display: flex;
            align-items: center;
            justify-items: space-between;
          "
              >
                <el-skeleton-item variant="text" style="margin-right: 16px" />
                <el-skeleton-item variant="text" style="width: 30%" />
              </div>
            </div>
          </template>
        </el-skeleton>
      </div>
    </MyPanel>
  </div>
</template>

<script>
import { ref, onMounted, watch } from "vue";
import MyPanel from "@/components/MyPanel.vue";
import { getSomeProducts, addProductToCart } from "@/api";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

export default {
  components: {
    MyPanel
  },
  setup() {
    const goods = ref([]);
    const router = useRouter();
    
    const fetchGoods = async () => {
      try {
        console.log('开始调用API: /api/products/someproducts');
        const res = await getSomeProducts();
        console.log('API完整响应:', res); // 完整的调试信息
        console.log('响应类型:', typeof res);
        
        // 检查响应数据的各个可能字段
        if (res) {
          if (res.code === 200) {
            console.log('状态码为200');
            // 检查不同的数据字段
            let productData = [];
            console.log('检查响应结构:', Object.keys(res));
            if (res.data && Array.isArray(res.data)) {
              console.log('使用data字段作为数据源');
              productData = res.data;
            } else if (res.result && Array.isArray(res.result)) {
              console.log('使用result字段作为数据源');
              productData = res.result;
            } else if (Array.isArray(res)) {
              console.log('直接使用响应作为数据源');
              productData = res;
            }
            
            // 处理商品数据
            if (Array.isArray(productData) && productData.length > 0) {
              console.log('设置商品数据，数量:', productData.length);
              // 过滤掉status不为1（下架）的商品
              const filteredProducts = productData.filter(item => item.status === 1);
              console.log('过滤后的商品数据，数量:', filteredProducts.length);
              goods.value = filteredProducts;
            } else {
              console.log('商品数据为空或不是数组:', productData);
              // 即使没有数据也确保数组格式
              goods.value = [];
            }
            
            // 强制触发视图更新
            console.log('触发视图更新，当前商品数量:', goods.value.length);
          } else {
            console.log('响应状态码不是200:', res.code);
            goods.value = [];
          }
        } else {
          console.log('响应为空');
          goods.value = [];
        }
        
        console.log('最终goods.value:', goods.value);
      } catch (error) {
        console.error("获取商品列表失败:", error);
        console.error("错误堆栈:", error.stack);
        console.error("错误名称:", error.name);
        console.error("错误信息:", error.message);
        goods.value = [];
      }
    };
    
    // 添加商品到购物车
    const addToCart = async (product) => {
      try {
        const res = await addProductToCart({
          productId: product.productId,
          quantity: 1
        });
        
        if (res.code === 200) {
          ElMessage.success('商品已添加到购物车');
        } else {
          ElMessage.error(res.message || '添加购物车失败');
        }
      } catch (error) {
        console.error("添加购物车失败:", error);
        ElMessage.error('添加购物车失败，请稍后重试');
      }
    };
    
    // 立即购买
    const buyNow = async (product) => {
      try {
        // 直接跳转到结算页面，并传递商品信息
        router.push({
          path: '/checkout',
          query: {
            productId: product.productId,
            productName: product.productName,
            price: product.price,
            imageUrl: product.imageUrl,
            quantity: 1
          }
        });
      } catch (error) {
        console.error("立即购买失败:", error);
        ElMessage.error('立即购买失败，请稍后重试');
      }
    };
    
    onMounted(() => {
      console.log('HomeGoods组件已挂载，开始获取商品数据');
      // 先使用测试数据验证组件是否能正常显示
      // goods.value = [
      //   {
      //     productId: 1,
      //     productName: '测试商品',
      //     price: 99.9,
      //     imageUrl: '',
      //     status: 1
      //   }
      // ];
      fetchGoods();
    });
    
    // 添加一个监视器来检查goods值的变化
    watch(goods, (newVal, oldVal) => {
      console.log('goods值发生变化:', oldVal, '->', newVal);
    }, { deep: true });
    
    return { goods, addToCart, buyNow };
  }
};
</script>

<style lang="less" scoped>
@import "@/assets/styles/variables.less";
@import "@/assets/styles/mixins.less";

.home-goods {
  .goods-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 40px;
    
    .item {
      width: 265px;
      height: 365px;
      background-color: #f5f5f5;
      margin-bottom: 20px;
      position: relative;
      
      .goods-container {
        padding: 10px;
        text-align: center;
        
        .goods-image {
          width: 100%;
          height: 200px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
          }
        }
        
        .goods-name {
          font-size: 16px;
          margin: 10px 0;
          height: 40px;
          line-height: 20px;
        }
        
        .goods-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 10px;
          margin-bottom: 10px;
          
          .price {
            font-size: 18px;
            color: @priceColor;
            font-weight: bold;
          }
          
          .add-cart-btn {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: @xtxColor;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
            font-weight: bold;
          }
        }
        
        .buy-btn {
          .purchase-btn {
            width: 90%;
            height: 35px;
            background-color: @xtxColor;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            
            &:hover {
              background-color: #b8884d;
            }
          }
        }
      }
      
      .hoverShadow();
    }
  }
  
  .skeleton-list {
    .el-skeleton {
      margin-bottom: 20px;
    }
  }
}
</style>